//
//  SearchResultViewController.m
//  u76ho
//
//  Created by m-air-01 on 16/1/30.
//  Copyright © 2016年 LV. All rights reserved.
//

#import "SearchResultViewController.h"
#import "RecommendCompanyCell.h"
#import "SpositionTableViewCell.h"
#import "SCompanyModel.h"
#import "SPositionModel.h"
#import "YiQiViewController.h"
#import "ZPDetailViewController.h"

@interface SearchResultViewController ()
<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>
{
    UITableView * _tableView;
    NSMutableArray * dataSource;
}
@property(nonatomic,strong)CCEaseRefresh * resresh;//下拉刷新

@end

static int page = 1;


@implementation SearchResultViewController

- (void)viewDidLoad {
    
//    UIBarButtonItem *backBarButton = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
//    
//    self.navigationItem.backBarButtonItem = backBarButton;
    
    

    
    
    [super viewDidLoad];
    [self main];
    //[self addBackItem];
    self.navigationItem.title = @"搜索结果";
    //[self addNavgationBar];
    // Do any additional setup after loading the view.
}
-(void)main
{
    self.view.backgroundColor = [UIColor whiteColor];
    dataSource = [[NSMutableArray alloc]init];
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, -1, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerNib:[UINib nibWithNibName:@"RecommendCompanyCell" bundle:nil] forCellReuseIdentifier:@"RecommendCompanyCell"];
    [_tableView registerNib:[UINib nibWithNibName:@"SpositionTableViewCell" bundle:nil] forCellReuseIdentifier:@"SpositionTableViewCell"];
    [self.view addSubview:_tableView];
    
    _tableView.tableFooterView = [UIView new];
    _tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
    self.automaticallyAdjustsScrollViewInsets = NO;
    page = 1;
    [self requestDataWithPage:page];
    
    __weak typeof(self)weakSelf = self;
    //下拉刷新
//    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        page = 1;
//        [weakSelf requestDataWithPage:page];
//    }];
//    
    self.resresh = [[CCEaseRefresh alloc] initInScrollView:_tableView];
    [self.resresh addTarget:self action:@selector(selfViewDidBeginRefreshing:) forControlEvents:UIControlEventValueChanged];
    
    [self.resresh beginRefreshing];
    

    
    
    //上拉加载
    _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf requestDataWithPage:++page];
    }];
}
#pragma mark -- 下拉刷新
- (void)selfViewDidBeginRefreshing:(CCEaseRefresh *)refreshControl {
    page = 1;
    
    double delayInSeconds = 1.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        
        [self requestDataWithPage:page];
       
        
        
        
    });
    
    
    
}
-(void)requestDataWithPage:(int)pages
{
    [self reachability];
    [U76HONet searchResultWithaction:@"" type:_type keyword:_keyWord industry:@"" page:[NSString stringWithFormat:@"%i",pages] pnum:@"15" yqlh:@"0" near:@"0" lng:@"" lat:@"" andDataBlock:^(NSArray *arr) {
        NSLog(@"搜索结果获取数据成功列");
        
        
        NSString * string =[NSString stringWithFormat:@"%i",pages];
        if ([string isEqualToString:@"1"]) {
            [dataSource removeAllObjects];
            [_tableView.mj_footer resetNoMoreData];
            
        }
        
        
        
        if ([_tableView.mj_footer isRefreshing])
        {
            if (arr.count) {
                [_tableView.mj_footer endRefreshing];
            }
            else
            {
                [_tableView.mj_footer endRefreshingWithNoMoreData];
                return ;
            }
        }
        
        if (arr.count == 0) {
            [self nosearch];
        }
        
        [dataSource addObjectsFromArray:arr];
        [_tableView reloadData];
        
        [self.resresh endRefreshing];

        
        
    }];

}
- (void)reachability
{
    // 检测网络连接状态
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    // 连接状态回调处理
    /* AFNetworking的Block内使用self须改为weakSelf, 避免循环强引用, 无法释放 */
    //    __weak typeof(self) weakSelf = self;
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
     {
         switch (status)
         {
             case AFNetworkReachabilityStatusUnknown:
                 // 回调处理
                 break;
             case AFNetworkReachabilityStatusNotReachable:
                 //                 [Singleton alerSendMessage:@""];
                 if ([_tableView.mj_header isRefreshing]) {
                     [_tableView.mj_header endRefreshing];
                 }
                 if ([_tableView.mj_footer isRefreshing])
                 {
                     [_tableView.mj_footer endRefreshing];
                 }
                 // 回调处理
                 break;
             case AFNetworkReachabilityStatusReachableViaWWAN:
                 // 回调处理
                 break;
             case AFNetworkReachabilityStatusReachableViaWiFi:
                 // 回调处理
                 break;
             default:
                 break;
         }
     }];
}
#pragma mark - _tableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([_type isEqualToString:@"comp"]) {
        RecommendCompanyCell * cell = [tableView dequeueReusableCellWithIdentifier:@"RecommendCompanyCell"];
        if (dataSource.count != 0) {
            SCompanyModel * model = dataSource[indexPath.row];
            cell.scompaymodel = model;
        }
        cell.isHiddenZP = @"YES";
        return cell;
    }
    else
    {
        SpositionTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"SpositionTableViewCell"];
        if (dataSource.count != 0) {
            SPositionModel * model = dataSource[indexPath.row];
            cell.model = model;
        }
        return cell;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([_type isEqualToString:@"comp"]) {
        return 75;
    }
    else
    {
        return 90;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    if ([self isLogin]) {
        if ([_type isEqualToString:@"comp"]) {
            SCompanyModel * model = [dataSource objectAtIndex:indexPath.row];
            YiQiViewController * companyVC = [[YiQiViewController alloc]init];
            companyVC.yqCode = model.code;
           // companyVC.MyTitle = model.companyname;
            [self.navigationController pushViewController:companyVC animated:YES];
        }
        else if([_type isEqualToString:@"duty"])
        {
            SPositionModel * model = [dataSource objectAtIndex:indexPath.row];
            ZPDetailViewController * zpDetailVC = [[ZPDetailViewController alloc]init];
            zpDetailVC.dutyId = model.ids;
            [self.navigationController pushViewController:zpDetailVC animated:YES];
        }
    }
}
-(BOOL)isLogin
{
    if ([Singleton share].code) {
        NSLog(@"登录了");
        return YES;
        
    }
    else
    {
        //        NSLog(@"还没登录呢");
        //        LoginViewController * loginVC = [[LoginViewController alloc]init];
        //        [self.navigationController pushViewController:loginVC animated:NO];
        //        return NO;
        if (SYSTEM_VERSION >= 8.0) {
            UIAlertController * alerVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还没有登录是否登录" preferredStyle:UIAlertControllerStyleAlert];
            [alerVC addAction:[UIAlertAction actionWithTitle:@"登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                
                LoginViewController * loginVC = [[LoginViewController alloc]init];
                UINavigationController *nvc = [[UINavigationController alloc]initWithRootViewController:loginVC];
                nvc.navigationBarHidden = YES;
                
                [self presentViewController:nvc animated:YES completion:nil];
            }]];
            [alerVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                
            }]];
            [self.view.window.rootViewController presentViewController:alerVC animated:YES completion:nil];
            
        }
        else
        {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您还没有登录是否登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert show];
        }
        return NO;
        
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    int i = (int)buttonIndex;
    if (i == 0) {
        
    }
    else if(i == 1)
    {
        LoginViewController * loginVC = [[LoginViewController alloc]init];
        UINavigationController *nvc = [[UINavigationController alloc]initWithRootViewController:loginVC];
        nvc.navigationBarHidden = YES;
        
        [self presentViewController:nvc animated:YES completion:nil];
    }
}
-(void)nosearch
{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    view.backgroundColor = UIColorFromRGB(0xf1f3f2);
    view.tag = 504;
    
    UIImageView * imgV = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2-98/2,SIZETO6H(120), 98, 100)];
    imgV.image = [UIImage imageNamed:@"苦脸"];
    [view addSubview:imgV];
    
    UILabel * tipLab = [[UILabel alloc]initWithFrame:CGRectMake(0, imgV.bottom+SIZETO6H(20), SCREEN_WIDTH, 20)];
    tipLab.text = @"暂时没有符合条件的内容";
    tipLab.textAlignment = NSTextAlignmentCenter;
    tipLab.font = [UIFont systemFontOfSize:14];
    tipLab.textColor = UIColorFromRGB(0x333944);
    [view addSubview:tipLab];
    [self.view addSubview:view];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
